<template>
  <div class="edit">
    <div class="titleTop first">
      <h3>{{$t('employing_unit.my')}}</h3>
      <a-button type="dashed" v-if="id"  @click="resetData()">{{$t('employing_unit.cancel_edit')}}</a-button>
      <template v-if="twoArrCludes(['ROLE_ADMIN'])">
        <span v-if="noEdit" class="noEdit blue" @click="()=>noEdit = false"><i class="iconfont icon-bianji"></i><span>{{$t('common.compile')}}</span></span>
        <a-button v-else type="primary" ghost @click="arrange('update')">{{$t('common.save')}}</a-button>
      </template>
    </div>
    <div class="content">
      <a-form :form="form" class="left">
        <a-card :title="template.group" v-for="template in templates && templates.filter(item => item.path !== 'contact' && item.visible)" :key="template.group">
          <a-row :gutter="24">
            <a-col v-for="record in template.fields.filter(item => item.path !== 'logo' && item.visible)" :key="record.path" class="formCol" :span="record.type === 'TEXT_AREA' || record.type === 'RICH_TEXTAREA' ? 24 : 12" >
              <a-form-item>
                <template slot="label" class="disposeLabel">
                  <a-tooltip>
                    <template slot='title'>
                      {{ record.name }}
                    </template>
                    {{ record.name }}
                  </a-tooltip>
                </template>
                <component
                  v-decorator="[record.key, {rules: [{ required: record.required, message: $t('common.pleaseEnter') + record.name }]}]"
                  :is="record.type"
                  :keys="record.key"
                  :placeholders="record.displayName"
                  :url='record.url'
                  :values='(record.enums && record.enums.length > 0) ? record.enums : (record.values && record.values.length > 0) ? record.values : []'
                  :unlimitedNumberValue="false"
                  :isDisabled="record.disabled || noEdit" />
              </a-form-item>
              <a-form-item :label="$t('employing_unit.fid_name')" v-if="record.path === 'fid'">
                  <a-tree-select
                    showSearch
                    style="width: 100%"
                    v-model="fid"
                    :placeholder="`${$t('common.choose')}${$t('employing_unit.fid_name')}`"
                    :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
                    allowClear
                    treeDefaultExpandAll
                    :treeData="companyList"
                    :disabled="$route.path === '/employingUnit/myEdit' || noEdit"
                  >
                  </a-tree-select>
                </a-form-item>
            </a-col>
          </a-row>
        </a-card>
      </a-form>
      <div class="right">
        <a-form :form="form" style="width: 420px">
          <a-card :title="$t('employing_unit.contact')" v-if="templates && templates.some(item => item.path === 'contact' && item.visible)">
            <template v-for="record in (templates && templates.filter(item => item.path === 'contact' && item.visible)[0].fields)">
              <a-form-item :key="record.path">
                <template slot="label" class="disposeLabel">
                  <a-tooltip>
                    <template slot='title'>
                      {{ record.name }}
                    </template>
                    {{ record.name }}
                  </a-tooltip>
                </template>
                <component
                  v-decorator="[record.key, {rules: [{ required: record.required, message: $t('common.pleaseEnter') + record.name }]}]"
                  :is="record.type"
                  :keys="record.key"
                  :placeholders="record.displayName"
                  :url='record.url'
                  :values='(record.enums && record.enums.length > 0) ? record.enums : (record.values && record.values.length > 0) ? record.values : []'
                  :unlimitedNumberValue="false"
                  :isDisabled="record.disabled || noEdit" />
              </a-form-item>
            </template>
            <template slot="actions" class="ant-card-actions">
              {{$t('employing_unit.last_updated_date')}}：{{lastUpdated}}
            </template>
          </a-card>
        </a-form>
        <a-card :title="$t('employing_unit.unit_logo')" style="width: 420px">
          <div class="logo">
            <a-row>
              <a-col :span="24">
                <a-upload
                  name="avatar"
                  listType="picture-card"
                  class="avatar-uploader"
                  :showUploadList="false"
                  :disabled="noEdit"
                  :beforeUpload="beforeUpload"
                  @change="handleChange"
                >
                  <img v-if="logo" :src="logo" alt="avatar" style="max-width: 100%"/>
                  <div v-else class="loginDiv">
                    <a-icon :type="loading ? 'loading' : 'plus'" />
                    <div class="ant-upload-text">{{$t('employing_unit.upload_logo')}}</div>
                  </div>
                </a-upload>
              </a-col>
            </a-row>
          </div>
        </a-card>
      </div>
    </div>
  </div>
</template>

<script>
import myUpload from 'vue-image-crop-upload'
import Editor from '@/components/Editor/Editor'
import TEXT_FIELD from '@/components/formComponents/TextField/TextField'
import MOBILE from '@/components/formComponents/Phone/Phone'
import EMAIL from '@/components/formComponents/Email/Email'
import RADIO_GROUP from '@/components/formComponents/RadioGroup/RadioGroup'
import CHECKBOX_GROUP from '@/components/formComponents/Checkbox/Checkbox'
import DATE from '@/components/formComponents/FormattingDate/FormattingDate'
import INT from '@/components/formComponents/Int/Int'
import TEXT_AREA from '@/components/formComponents/TEXT_AREA/TEXT_AREA'
import SELECT from '@/components/formComponents/Select/Select'
import DEPARTMENT from '@/components/formComponents/Department/Department'
import SELECT_URL from '@/components/formComponents/SelectUrl/SelectUrl'
import RICH_TEXTAREA from '@/components/formComponents/RichTextarea/RichTextarea'
import JOB_TYPE from '@/components/formComponents/JobType/JobType'
import CHECKBOX from '@/components/formComponents/jobTypeCheckbox/jobTypeCheckbox'
import image64 from '@/assets/image-64.js'
import { mapState } from 'vuex'
// import FILE_UPLOAD from '@/components/formComponents/fileUpload/fileUpload' // 当前组件不符合图片处理形式
// import Editor from '@/components/Editor/Editor'
import AddAcct from '@/components/Config/AddAcct'
import { detail, updateCompany, findFieldGroups } from '@/api/employingUnit'
import { twoArrCludes } from '@/util/roles'
export default {
  name: 'edit',
  components: { AddAcct, myUpload, Editor, TEXT_FIELD, MOBILE, EMAIL, RADIO_GROUP, CHECKBOX_GROUP, DATE, INT, TEXT_AREA, SELECT, DEPARTMENT, SELECT_URL, RICH_TEXTAREA, JOB_TYPE, CHECKBOX },
  data () {
    return {
      combine: {},
      image64,
      templates: null,
      form: this.$form.createForm(this),
      formItemLayout: {
        labelCol: { span: 3 },
        wrapperCol: { span: 21 }
      },
      lastUpdated: '',
      noEdit: true,
      id: '',
      name: '',
      status: '',
      loading: false,
      logos: false,
      logo: '',
      description: '',
      fid: '',
      record: null,
      logoType: '',
      enterpriseId: '',
      // dataCount: {
      //   positionCount: 0, // 职位数量
      //   applicationCount: 0, // 简历投递数量
      //   recruitAccountCount: 0 // 招聘主账号数量
      // },
      dataTmp: {},
      titleFileName: '',
      companyList: [],
      managers: {}
    }
  },
  created () {
    this.getTemplate()
  },
  computed: {
    ...mapState({
      userInfo: state => state.user.userInfo
    })
  },
  methods: {
    // ...mapMutations('user', ['SET_USER_INFO']),
    twoArrCludes,
    filterFields (fields) {
      return fields.filter(item => item.path !== 'logo')
    },
    // initOperate () {
    //   this.$nextTick(() => {
    //     let id = this.$route.query.id
    //     if (id) {
    //       this.id = id
    //       this.getUnit()
    //       // this.getEnterpriseCount()
    //     }
    //     let fid = this.$route.query.fid
    //     if (fid) {
    //       this.fid = fid
    //     }
    //     if (this.$route.path === '/employingUnit/myEdit') {
    //       this.getUnit()
    //     }
    //   })
    // },
    async getTemplate () {
      let res = await findFieldGroups()
      if (res.code === 200) {
        this.templates = res.data
        this.getUnit()
      } else {
        this.$message.error(res.message)
      }
    },
    // filterRole2 (roles) {
    //   return !this.userInfo.role.every(item => roles.includes(item))
    // },
    // filterRole (roles) {
    //   return !this.userInfo.role.every(item => item === roles)
    // },
    // pushPath (path) {
    //   this.$router.push(path + `?enterpriseId=${this.id}`)
    // },
    // goUnit () {
    //   this.$router.push('/employingUnit/employingUnitList')
    // },
    resetData () {
      this.$router.push('/employingUnit/employingUnitList')
    },
    // getCompanyList (arr) {
    //   return arr.map(item => {
    //     let obj = {
    //       title: item.name,
    //       value: item.id,
    //       key: item.id
    //     }
    //     if (item.children) {
    //       obj.children = this.getCompanyList(item.children)
    //     }
    //     return obj
    //   })
    // },
    // async getEnterpriseCount () {
    //   this.loading = true
    //   let params = {
    //     enterpriseId: this.dataTmp.enterpriseId
    //   }
    //   let res = await enterpriseCount(params)
    //   if (res.code === 200) {
    //     this.dataCount = res.data
    //   } else {
    //     this.$message.error(res.message)
    //   }
    //   this.loading = false
    // },
    // data2blob (data) {
    //   data = data.split(',')[1]
    //   data = window.atob(data)
    //   var ia = new Uint8Array(data.length)
    //   for (var i = 0; i < data.length; i++) {
    //     ia[i] = data.charCodeAt(i)
    //   }
    //   // canvas.toDataURL 返回的默认格式就是 image/png
    //   return new File([new Blob([ia], {
    //     type: this.logoType
    //   })], this.titleFileName)
    // },
    arrange (type) {
      this.form.validateFields(async (err, values) => {
        if (!err) {
          // if (this.logos) {
          //   let fmData = new FormData()
          //   fmData.append('enterpriseId', values.enterpriseId)
          //   fmData.append('file', this.data2blob(this.logo))
          //   // let params = {
          //   //   enterpriseId: values.enterpriseId,
          //   //   file: this.data2blob(this.logo)
          //   // }
          //   let res = await uploadLogo(fmData)
          //   if (res.code === 200) {
          //     this.logo = res.data.filePath
          //   } else {
          //     this.$message.error(res.message)
          //     return false
          //   }
          // }
          let params = values
          params.logo = this.logo
          this[type](params)
          this.noEdit = true
        }
      })
    },
    control (res) {
      if (res.code === 200) {
        if (this.$route.path === '/employingUnit/myEdit') {
          this.getUnit()
        } else {
          this.$router.push('/employingUnit/employingUnitList')
        }
        this.$message.success(res.message)
      } else {
        this.$message.error(res.message)
      }
    },
    async update (values) {
      let params = {
        content: values
      }
      let res = await updateCompany(params)
      this.control(res)
    },
    // async add (values) {
    //   this.loading = true
    //   let params = {
    //     ...values
    //   }
    //   let res = await saveCompany(params)
    //   this.control(res)
    // },
    // setfield (data) {
    // },
    async getUnit () { // 获取公司信息
      this.loading = true
      let params = {
        id: this.id || null
      }
      let res = await detail(params)
      if (res.code === 200) {
        this.dataTmp = JSON.parse(JSON.stringify(res.data))
        this.form.setFieldsValue(res.data.content || {})
        this.operateData(res.data.content || {})
        this.lastUpdated = res.data.lastUpdated
      } else {
        this.$message.error(res.message)
      }
      this.loading = false
    },
    operateData (obj) {
      // this.form.setFieldsValue({
      //   name: obj.name
      //   // 单位行业
      // })
      this.logo = obj.logo
      this.description = obj.description
    },
    // editorReady (quill, editorName) {
    //   // this[editorName] = quill
    // },
    getBase64 (img, callback) {
      const reader = new FileReader()
      reader.addEventListener('load', () => callback(reader.result))
      reader.readAsDataURL(img)
    },
    handleChange (info) {
      this.getBase64(info.file.originFileObj, logo => {
        if (this.logo !== logo) {
          this.titleFileName = info.file.name
          this.logoType = info.file.type
          this.logo = logo
          this.logos = true
        }
        this.loading = false
      })
    },
    beforeUpload (file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
      if (!isJpgOrPng) {
        this.$message.error(`${this.$t('employing_unit.only_image')}!`)
        return isJpgOrPng
      }
      const isLt2M = file.size / 1024 < 256
      if (!isLt2M) {
        this.$message.error(`${this.$t('employing_unit.only_50kb')}!`)
        return isLt2M
      }
    }
  }
}
</script>
<style lang="stylus" scoped>
@import '../../styles/var.styl'
.edit
  .ffr
    margin-left auto!important
  .titleTop
    background #fff
    display flex
    align-items center
    justify-content flex-start
    padding  0 24px 12px
    h3
      margin-right 24px
      font-size 18px
      font-weight bold
    button
      margin-left 12px
  .noEdit
    margin-left 12px
    cursor pointer
    i
      margin-right 4px
      vertical-align middle
    span
      vertical-align middle
  .content
    display flex
    padding 12px 24px
    :global(.editor_wrapper)
      line-height normal
      margin-top 24px
    .right
      margin-left 24px
    .left
      flex 1
    .ant-card
      margin-top 12px
      &:first-child
        margin 0
    .logo
      display flex
    .ant-row
      flex 1
      .ant-col-3
        text-align right
        font-weight bold
      :global(.ant-upload-select-picture-card)
        width 100%
  .fisrt
    width 420px
    p
      line-height 28px
    div.firstContent
      display flex
      >div:first-child
        width 93px
        height 93px
        margin-right 10px
        border 1px solid borderColor
        img
          width 100%
          height 100%
  .second
    // width 300px
    p
      line-height 28px
  .red
    color errorColor
    text-decoration underline
  .blue
    color var(--blue-500)
    cursor pointer
  .under
    text-decoration underline
</style>
